<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">批量上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">批量下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" height="700"  @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55" fixed>
      </el-table-column>
      <el-table-column type="index" width="60" fixed>
      </el-table-column>
      <el-table-column prop="title" label="标题" fixed width="180" sortable>
      </el-table-column>
      <el-table-column prop="cover" label="封面" width="120" sortable>
        <template slot-scope="scope">
          <img :src="scope.row.cover" style="width:50px;height:50px;"/>
        </template>
      </el-table-column>
      <el-table-column prop="saleprice" label="原价" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="售价" width="120" sortable>
      </el-table-column>
      <el-table-column prop="isnew" label="是否新车" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.isnew == 0">二手车</span>
          <span v-if="scope.row.isnew == 1">新车</span>
        </template>
      </el-table-column>
      <el-table-column prop="reigstertime" label="注册时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="mileage" label="里程数" width="120" sortable>
      </el-table-column>
      <el-table-column prop="shopname" label="店铺名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: blue">上架</span>
          <span v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="costeffective" label="超值" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.costeffective == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="rushsale" label="急售" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.rushsale == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="quasinewcar" label="准新车" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.quasinewcar == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="transitivecountry" label="可提全国" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.transitivecountry == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="type.name" label="类型" width="100" sortable>
      </el-table-column>
      <el-table-column prop="seller.realName" label="营销人员" width="100" sortable>
      </el-table-column>
      <el-table-column prop="auditstate" label="审核状态" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.auditstate == 1">已审核</span>
          <span v-else>未审核</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150"  fixed="right">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <br/>
          <el-button size="small" v-if="scope.row.state == 0 && scope.row.auditstate == 1" @click="handleEdit(scope.$index, scope.row)">上架</el-button>
          <el-button type="danger" size="small"  v-if="scope.row.state == 1" @click="handleDel(scope.$index, scope.row)">下架</el-button>
          <br/>
          <el-button type="danger" size="small" style="margin-top:10px;" @click="handleResource(scope.$index, scope.row)">资源维护</el-button>
          <br/>
          <el-button type="danger" size="small" style="margin-top:10px;" @click="handleDel(scope.$index, scope.row)">上传检测报告</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          :current-page="query.currentPage"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增/修改界面-->
    <el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="carForm" label-width="80px" :rules="saveFormRules" ref="carForm">
        <el-form-item label="标题">
          <el-input v-model="carForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="coverHandleRemove"
              :on-success="coverHandleSuccess"
              :file-list="coverFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="carForm.saleprice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="carForm.costprice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否新车">
          <el-radio-group v-model="carForm.isnew">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上牌时间">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="carForm.reigstertime"
              type="date"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="里程数">
          <el-input v-model="carForm.mileage" style="width:220px;" type="number" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="超值">
          <el-radio-group v-model="carForm.costeffective">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="急售">
          <el-radio-group v-model="carForm.rushsale">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="准新车">
          <el-radio-group v-model="carForm.quasinewcar">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可迁全国">
          <el-radio-group v-model="carForm.transitivecountry">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-cascader v-model="carForm.type"
                       :options="carTypeTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="基本信息">
          <!--<el-input type="textarea" v-model="carForm.carDetail.info"></el-input>-->
          <quill-editor v-model="carForm.carDetail.info" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="资源维护" :visible.sync="carResourceVisible" :close-on-click-modal="false">
      <el-form label-width="80px" ref="carResourceForm">
        <el-form-item label="主图">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="imgHandleRemove"
              :on-success="imgHandleSuccess"
              :file-list="imgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="副图">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="viceimgHandleRemove"
              :on-success="viceimgHandleSuccess"
              :file-list="viceimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!--file-list 用来做回显的,就是将后端查出来的图片信息,封装成数组,赋值给file-list,它就能回显了-->
        <el-form-item label="更多图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="moreimgHandleRemove"
              :on-success="moreimgHandleSuccess"
              :file-list="moreimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carResourceVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveCarResource" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
// 引入富文本编辑器的相关组件
import {quillEditor} from "vue-quill-editor"
import quillConfig from "../../common/js/quill-config.js"

// 引入富文本编辑器的样式
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css"
export default {
  components:{
    //quillEditor:quillEditor
    quillEditor
  },
  data() {
    return {
      quillOption:quillConfig,
      listLoading: false,
      sels: [],//列表选中列
      saveFormVisible: false,//新增界面是否显示
      addLoading: false,
      saveFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入标识', trigger: 'blur' }
        ]
      },
      query:{
        currentPage:1,
        pageSize:100,
        keyword:""
      },
      pageInfo:{
        rows:[],
        total:0
      },
      coverFileList:[],   // 封面图片的图片列表
      carForm: {
        id:null,
        title:"",
        cover:"",
        saleprice:0,
        costprice:0,
        isnew:0,
        reigstertime:"",
        mileage:null,
        costeffective:0,
        rushsale:0,
        quasinewcar:0,
        transitivecountry:0,
        type:{
          id:null,
          name:""
        },
        typeId:null,
        carDetail:{
          info:""
        }
      },
      carTypeTree:[],

      carResourceVisible:false,
      carId:null,
      carResourceList:[],
      imgFileList:[],
      viceimgFileList:[],
      moreimgFileList:[]
    }
  },
  methods: {
    // 批量上架的方法
    onsale(){
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      // 获取当前选中行的id
      var ids = this.sels.map(item => item.id);

      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/car/onsale',ids).then((res) => {
          this.listLoading = false;
          res = res.data;   // {success:true,message:"",resultObj}
          if(res.success){
            this.$message({
              message: res.message,
              type: 'success'
            });
            // 刷新页面
            this.getCars();
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            });
          }
        });
      }).catch(() => {

      });
    },
    // 批量下架
    offsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/car/offsale',ids).then((res) => {
          this.listLoading = false;
          res = res.data;
          if(res.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
            this.getCars();
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            });
          }
        });
      }).catch(() => {

      });
    },

    search(){
      // 点击 查询时,应该重新从第一页开始查询
      this.query.currentPage = 1;
      this.getCars();
    },
    handleCurrentChange(val) {
      // val 当前跳转的页码
      this.query.currentPage = val;
      this.getCars();
    },

    coverHandleRemove(file, fileList){
      var filePath = file.response.resultObj;
      this.$http.delete("/fastDfs/delete?path="+filePath)
          .then(result => {
            result = result.data;
            if(result.success){
              this.$message({message: '删除成功!', type: 'success'});
              this.carForm.cover = "";
            }else{
              this.$message({message: result.message, type: 'error'});
            }
          })
    },
    coverHandleSuccess(response, file, fileList){
      this.carForm.cover = response.resultObj;
    },

    saveCarResource(){
      // 封装得到后端需要的对象数组
      this.dealCarResource();
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.addLoading = true;
        this.$http.put("/carResources",this.carResourceList)
            .then(result => {
              result = result.data;
              if(result.success){
                // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
                this.addLoading = false;
                // 关闭弹框
                this.carResourceVisible = false;
                this.$message({message: '保存成功!', type: 'success'});
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })
      });
    },
    handleResource(index,row){
      // 给文件数组赋空值,防止将上一次的内容带到这一次
      this.imgFileList = [];
      this.viceimgFileList = [];
      this.moreimgFileList = [];
      // 展示弹框
      this.carResourceVisible = true;
      this.carId = row.id;
      // 根据车辆的ID查询该车辆的资源信息,如果有就要回显
      this.getCarResourcesByCarId(row.id);
    },
    getCarResourcesByCarId(carId){
      this.$http.get("/carResources/carid/"+carId)
          .then(result => {
            result = result.data;
            if(result.success){
              for(let i=0;i<result.resultObj.length;i++){
                 let obj = result.resultObj[i];
                 let imgurl = obj.resourceUrl; // 取图片的路径
                 let name = imgurl.substring(imgurl.lastIndexOf("/")+1);
                 if(obj.type == 1){ // 说明当前是主图
                    let file = {name:name,url:imgurl,response:{success:true,message:"",resultObj:imgurl}};
                    this.imgFileList.push(file)
                 }
                if(obj.type == 2){ // 说明当前是副图
                  this.viceimgFileList.push({name:name,url:imgurl,response:{success:true,message:"",resultObj:imgurl}})
                }
                if(obj.type == 3){ // 说明当前是更多图片
                  this.moreimgFileList.push({name:name,url:imgurl,response:{success:true,message:"",resultObj:imgurl}})
                }
              }
            }
          })
    },
    dealCarResource(){
      // 将主图 副图 更多图片 封装成一个一个的CarResource对象  carId,resourceUrl,type
      // 处理主图
      for(let i=0;i<this.imgFileList.length;i++){
        let obj = this.imgFileList[i].response;
        this.carResourceList.push({carId:this.carId,resourceUrl:obj.resultObj,type:1});
      }
      // 处理副图
      for(let i=0;i<this.viceimgFileList.length;i++){
        let obj = this.viceimgFileList[i].response;
        this.carResourceList.push({carId:this.carId,resourceUrl:obj.resultObj,type:2});
      }
      // 处理更多图片
      for(let i=0;i<this.moreimgFileList.length;i++){
        let obj = this.moreimgFileList[i].response;
        this.carResourceList.push({carId:this.carId,resourceUrl:obj.resultObj,type:3});
      }
    },

    // 主图删除
    // file 当前要删除的这个文件对象
    // fileList  删除当前文件后,剩余的文件对象数组
    imgHandleRemove(file, fileList){
      var filePath = file.response ? file.response.resultObj : file.url;
      this.imgFileList = fileList;
      this.$http.delete("/fastDfs?path="+filePath)
          .then(result => {
            result = result.data;
            if(result.success){
              this.$message({message: '删除成功!', type: 'success'});
            }else{
              this.$message({message: result.message, type: 'error'});
            }
          })
    },
    // response  上传成功当前图片后,后端接口返回的信息 {success,message,resultObj:"fastdfs返回的url"}
    // file 当前上传成功的文件对象,它里面包含response
    // fileList 当前这个文件上传组件,上传成功的所有的图片信息
    imgHandleSuccess(response, file, fileList){
      this.imgFileList = fileList;
      console.log("主图",fileList);
      console.log(this.imgFileList)
    },

    viceimgHandleRemove(file, fileList){
      var filePath = file.response.resultObj;
      this.viceimgFileList = fileList;
      this.$http.delete("/fastDfs?path="+filePath)
          .then(result => {
            result = result.data;
            if(result.success){
              this.$message({message: '删除成功!', type: 'success'});
            }else{
              this.$message({message: result.message, type: 'error'});
            }
          })
    },
    viceimgHandleSuccess(response, file, fileList){
      this.viceimgFileList = fileList;
    },

    moreimgHandleRemove(file, fileList){
      var filePath = file.response.resultObj;
      this.moreimgFileList = fileList;
      this.$http.delete("/fastDfs/delete?path="+filePath)
          .then(result => {
            result = result.data;
            if(result.success){
              this.$message({message: '删除成功!', type: 'success'});
            }else{
              this.$message({message: result.message, type: 'error'});
            }
          })
    },
    moreimgHandleSuccess(response, file, fileList){
      this.moreimgFileList = fileList;
    },
    //获取角色列表
    getCars() {
      // 通过axios调用后端分页接口
      this.$http.post("/car",this.query)
          .then(result => {
            result = result.data;
            if(result.success){
              // 要展示table的数据,渲染分页条
              this.pageInfo = result.resultObj;
            }
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/car/"+row.id)
            .then(result => {
              result = result.data;
              if(result.success){
                // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
                this.listLoading = false;
                // 从第一页开始重新进行查询
                this.search()
                this.$message({message: '删除成功!', type: 'success'});
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })
      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      // 显示弹框
      this.saveFormVisible = true;
      // row就是当前行对象,所以直接将row赋值给this.saveForm就可以实现回显
      this.saveForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      // 显示弹框
      this.saveFormVisible = true;
      // 将this.saveForm中的值赋空值
      this.carForm = {
        id:null,
        title:"",
        cover:"",
        saleprice:0,
        costprice:0,
        isnew:0,
        reigstertime:"",
        mileage:null,
        costeffective:0,
        rushsale:0,
        quasinewcar:0,
        transitivecountry:0,
        type:{
          id:null,
          name:""
        },
        typeId:null,
        carDetail:{
          info:""
        }
      }
      // 查询车辆类型的树
      this.getCarTypeTree();
    },
    getCarTypeTree(){
      this.$http.get("/carType/tree")
          .then(result => {
            result = result.data;
            if(result.success){
              this.carTypeTree = result.resultObj;
            }
          })
    },
    //新增/修改的保存操作
    save: function () {
      this.$refs.carForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            var param = this.carForm;
            var array = param.type;
            if(array && array.length > 0){
              param.type = {id:array[array.length-1]}   // {id:27}
            }
            this.addLoading = true;
            this.$http.put("/car",param)
                .then(result => {
                  result = result.data;
                  this.addLoading = false;
                  if(result.success){
                    // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
                    this.addLoading = false;
                    // 关闭弹框
                    this.saveFormVisible = false;
                    // 从第一页开始重新进行查询
                    this.search();
                    this.$message({message: '保存成功!', type: 'success'});
                  }else{
                    this.$message({message: result.message, type: 'error'});
                  }
                })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      // 拿到要删除行的ID  this.sels是当前被勾选中的多选框的所有行的对象
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/car",ids)
            .then(result => {
              result = result.data;
              if(result.success){
                // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
                this.listLoading = false;
                // 从第一页开始重新进行查询
                this.search();
                this.$message({message: '删除成功!', type: 'success'});
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getCars();
  }
}

</script>

<style scoped>

</style>